<?php
/**
 * Author: xx.com
 * Date: 2015-09-09
 */

namespace Home\Logic;

use Think\Model\RelationModel;
use Think\Page;
use Think\Log;


/**
 * 分类逻辑定义
 * Class CatsLogic
 * @package Home\Logic
 */
class UsersLogic extends RelationModel
{
    /*
     * 登陆
     */
    public function login($username,$password){
    	$result = array();
        if(!$username || !$password)
           $result= array('status'=>0,'msg'=>'请填写账号或密码');
        $user = M('users')->where("mobile='{$username}' OR email='{$username}'")->find();
        if(!$user){
           $result = array('status'=>-1,'msg'=>'账号不存在!');
        }elseif($password != $user['password']){
           $result = array('status'=>-2,'msg'=>'密码错误!');
        }elseif($user['is_lock'] == 1){
           $result = array('status'=>-3,'msg'=>'账号异常已被锁定！！！');
        }else{
            //查询用户信息之后, 查询用户的登记昵称
            $levelId = $user['level'];
            $levelName = M("user_level")->where("level_id = {$levelId}")->getField("level_name"); 
            $user['level_name'] = $levelName;
            if($user['is_distribut'] == 1)
                $user['share_link'] = $this->getShareLink($user);
            $result = array('status'=>1,'msg'=>'登陆成功','result'=>$user);
        }
        return $result;
    }

    /*
     * app端登陆
     */
    public function app_login($username,$password){
    	$result = array();
        if(!$username || !$password)
           $result= array('status'=>0,'msg'=>'请填写账号或密码');
        $user = M('users')->where("mobile='{$username}' OR email='{$username}'")->find();
        if(!$user){
           $result = array('status'=>-1,'msg'=>'账号不存在!');
        }elseif($password != $user['password']){
           //前端加密
           $result = array('status'=>-2,'msg'=>'密码错误!');
        }elseif($user['is_lock'] == 1){
           $result = array('status'=>-3,'msg'=>'账号异常已被锁定！！！');
        }else{
            //查询用户信息之后, 查询用户的登记昵称
            $levelId = $user['level'];
            $levelName = M("user_level")->where("level_id = {$levelId}")->getField("level_name"); 
            $user['level_name'] = $levelName;            
            $user['token'] = md5(time().mt_rand(1,999999999));
            M('users')->where("user_id = {$user['user_id']}")->save(array('token'=>$user['token'],'last_login'=>time()));
            if($user['is_distribut'] == 1)
                $user['share_link'] = $this->getShareLink($user);
            $user['head_pic'] = parseMediaUrl($user['head_pic']);

            $result = array('status'=>1,'msg'=>'登陆成功','result'=>$user);
        }
        return $result;
    }    
    
    
    //绑定账号
    public function oauth_bind($data = array())
    {
    	$user = session('user');
    	if(empty($user['openid'])){
    		if(M('users')->where(array('openid'=>$data['openid']))->count()>0){
    			return array('status'=>-1,'msg'=>'您的'.$data['oauth'].'账号已经绑定过账号');
    		}else{
    			 M('users')->where(array('user_id'=>$user['user_id']))->save($data);
    			 return array('status'=>1,'msg'=>'绑定成功','result'=>$data);
    		}
    	}else{
    		return array('status'=>-1,'msg'=>'您的账号已绑定过，请不要重复绑定');
    	}
    }
    /*
     * 第三方登录
     */
    public function thirdLogin($data=array()){
        M()->startTrans();
        $openid = $data['openid']; //第三方返回唯一标识
        $oauth = $data['oauth']; //来源
        $coordinate_xy = $data['coordinate_xy']; // 用户经纬度
        $find['openid'] = $openid;
        $find['oauth'] = $oauth;
        $user = M('users')->where($find)->find();
        if(!$user){
            //账户不存在 注册一个
            $map['password'] = md5('123456');
            $map['openid'] = $openid;
            $map['nickname'] = $data['nickname'];
            $map['reg_time'] = time();
            $map['oauth'] = $oauth;
            $map['coordinate_xy'] = $coordinate_xy;
            $map['head_pic'] = $data['head_pic'];
            $map['sex'] = empty($data['sex']) ? 0 : $data['sex'];
            $map['token'] = md5(time().mt_rand(1,99999));
            $map['leader'] = $this->createInCode();
            $map['first_leader'] = cookie('first_leader'); // 推荐人id
            if($_GET['first_leader'])
                $map['first_leader'] = $_GET['first_leader']; // 微信授权登录返回时 get 带着参数的            
            // 如果找到他老爸还要找他爷爷他祖父等
            if($map['first_leader'])
            {
                $first_leader = M('users')->where("user_id = {$map['first_leader']}")->find();
                $map['second_leader'] = $first_leader['first_leader']; //  第一级推荐人
                $map['third_leader'] = $first_leader['second_leader']; // 第二级推荐人
            }else
			{
				$map['first_leader'] = 0;
			}                                    

            // 成为分销商条件  
            $distribut_condition = tpCache('distribut.condition'); 
            if($distribut_condition == 0)  // 直接成为分销商, 每个人都可以做分销        
                $map['is_distribut']  = 1;
                        
            $row_id = M('users')->add($map);
            if ($row_id){
                #注册环信
//                 $Easemob = new \Common\Util\Easemob;
//                 $im_user = $row_id;
//                 $password = $map['password'];
//                 $im_passwd = $password;
//                 $regIm = $Easemob->createUser( $im_user, $im_passwd );
// 
//                 if(!$regIm)
//                 {
//                     M()->rollback();
//                     return array('status'=>-1,'msg'=>'注册失败');
//                 }

                $pay_points_self = tpCache('basic.reg_integral_self'); // 注册赠送积分
                if($pay_points_self&&$pay_points_self > 0)
                {
                    accountLog($row_id,0,$pay_points_self,'注册奖励');
                }

                #第三方注册无法追踪推荐，不进行上级奖励

                M()->commit();
            }
			$user = M('users')->where("user_id = '$row_id'")->find();
        }else{
            $where['openid'] = $data['openid'];
            $user_id = M('users')->field('user_id')->where($where)->find();
            $user['token'] = md5(time().mt_rand(1,999999999));
            unset($where);
            $where['user_id'] = $user_id['user_id'];
            $res =  M('users')->where($where)->save(array('coordinate_xy'=>$coordinate_xy,'token'=>$user['token'],'last_login'=>time())); 
            $user = M('users')->where($where)->find();
        }

        if(!$user)
        {
            return array(
                'status'=>-1,
                'msg'=>'登陆失败',
                'result'=>''
            );
        }
        M()->commit();
        if($user['is_distribut'] == 1)
            $user['share_link'] = $this->getShareLink($user);
        return array('status'=>1,'msg'=>'登陆成功','result'=>$user);
   }

    /**
     * 注册
     * @param $username  邮箱或手机
     * @param $password  密码
     * @param $password2 确认密码
     * @return array
     */
    public function reg($username,$password,$password2, $leader = 0){
        
        if ($leader) {
            $leaders = M('users')->where([
                "leader" => $leader
            ])->field('user_id,pay_points')->find();
            
            if($leaders) 
            {
                $leader = $leaders['user_id'];
            }else{
                $leader = 0;
            }
        }else{
            $leader = 0;
        }

        if(check_email($username)){
            $is_validated = 1;
            $map['email_validated'] = 1;
            $map['nickname'] = $map['email'] = $username; //邮箱注册
        }

        if(check_mobile($username)){
            $is_validated = 1;
            $map['mobile_validated'] = 1;
            $map['mobile'] = $username; //手机注册
            $map['nickname'] = 'tsb_'.substr($map['mobile'],6);
        }

        if($is_validated != 1)
            return array('status'=>-1,'msg'=>'请用手机号或邮箱注册');

        if(!$username || !$password)
            return array('status'=>-1,'msg'=>'请输入用户名或密码');

        //验证两次密码是否匹配
        if($password2 != $password)
            return array('status'=>-1,'msg'=>'两次输入密码不一致');
        //验证是否存在用户名
        if(get_user_info($username,1)||get_user_info($username,2))
            return array('status'=>-10010,'msg'=>'账号已存在');

        $map['password'] = $password;
        $map['reg_time'] = time();
        if($leader){
            $map['first_leader'] = $leader;
        }else{
            $map['first_leader'] = cookie('first_leader'); // 推荐人
        }

        // 如果找到他老爸还要找他爷爷他祖父等
        if($map['first_leader'])
        {
            $first_leader = M('users')->where("user_id = {$map['first_leader']}")->find();
            $map['second_leader'] = $first_leader['first_leader'];
            //三级分销->二级分销
            //$map['third_leader'] = $first_leader['second_leader'];
        }else
		{
			$map['first_leader'] = 0;
		}
        
        // 成为分销商条件  
        $distribut_condition = tpCache('distribut.condition'); 
        if($distribut_condition == 0)  // 直接成为分销商, 每个人都可以做分销        
            $map['is_distribut']  = 1;        
        
        $map['token'] = md5(time().mt_rand(1,99999));
        #生成邀请码
        $map['leader'] = $this->createInCode();

        #开启事务
        M()->startTrans();
        $user_id = M('users')->add($map);
        if(!$user_id)
        {
            M()->rollback();
            return array('status'=>-1,'msg'=>'注册失败');
        }


        $user = M('users')->where(["user_id"=>$user_id])->find();
        #注册环信
        $Easemob = new \Common\Util\Easemob;
        $im_user = $user['user_id'];
        $im_passwd = $password;
        $im_nickname = $user['nickname'];
        $regIm = $Easemob->createUser( $im_user, $im_passwd,$im_nickname );
        if(!$regIm)
        {
            M()->rollback();
            return array('status'=>-1,'msg'=>'注册失败');
        }

        $pay_points_self = tpCache('basic.reg_integral_self'); // 注册赠送积分
        if($pay_points_self&&$pay_points_self > 0)
        {
            accountLog($user['user_id'],0,$pay_points_self,'注册奖励');
        }

        if ($leader) {            
            $pay_points = tpCache('basic.reg_integral'); // 推荐注册赠送积分
            if($pay_points > 0)
            {
                accountLog($leader,0,$pay_points,'推荐'.$username.'注册');
            }
        }

        M()->commit();
        return array('status'=>1,'msg'=>'注册成功','result'=>$user);
    }

     /*
      * 获取当前登录用户信息
      */
     public function get_info($user_id){
         if(!$user_id > 0)
             return array('status'=>-1,'msg'=>'缺少参数','result'=>'');
         $user_info = M('users')->where("user_id = {$user_id}")->find();
         $user_info['level_name'] = $this->getLevelName($user_info['level']);

        if(!$user_info)
            return false;

        if($user_info['is_distribut'] == 1)
            $user_info['share_link'] = $this->getShareLink($user_info);
        $user_info['coupon_price'] = $user_info['pay_points'];//我的积分
        $user_info['collect_count'] = M('goods_collect')->where(array('user_id'=>$user_id))->count(); //获取收藏数量         
                                   
        $user_info['waitPay']     = M('order')->where("user_id = $user_id".C('WAITPAY')."and parent_sn!='0'")->count(); //待付款数量
        $user_info['waitSend']    = M('order')->where("user_id = $user_id ".C('WAITSEND')."and parent_sn!='0'")->count(); //待发货数量
        $user_info['waitReceive'] = M('order')->where("user_id = $user_id ".C('WAITRECEIVE')."and parent_sn!='0'")->count(); //待收货数量
        $user_info['cancel'] = M('order')->where("user_id = $user_id ".C('CANCEL')."and parent_sn!='0'")->count();//取消数量
        $user_info['comment'] = M('order')->where("user_id = $user_id ".C('WAITCCOMMENT')."and parent_sn!='0'")->count();//待评价
        $user_info['order_count'] = $user_info['waitPay'] + $user_info['waitSend'] + $user_info['waitReceive']+$user_info['cancel']+$user_info['comment'];
        
        $user_info['head_pic'] = parseMediaUrl($user_info['head_pic']);
		// 查询所有积分
		$where_account['user_id'] = $user_id;
		$where_account['pay_points'] = ['GT',0];
		// p($where_account);
		$user_info['all_account_log'] = M('account_log')->where($where_account)->sum('pay_points');
		// p(M('account_log')->where($where_account)->select());die;
         unset($user_info['password']);
        return array('status'=>1,'msg'=>'获取成功','result'=>$user_info);
     }
     
    /*
     * 获取最近一笔订单
     */
    public function get_last_order($user_id){
        $last_order = M('order')->where("user_id = {$user_id}")->order('order_id DESC')->find();
        return $last_order;
    }


    /*
     * 获取订单商品
     */
    public function get_order_goods($order_id, $is_allow_drawback = 0){
        $sql = "SELECT og.*,g.original_img FROM ln_order_goods og LEFT JOIN ln_goods g ON g.goods_id = og.goods_id WHERE order_id = ".$order_id;
        $goods_list = $this->query($sql);
        foreach ($goods_list as $key => &$glv) 
        {
            $glv['original_img'] = parseMediaUrl($glv['original_img']);
            $glv['allow_draw_btn'] = ($is_allow_drawback == 1 && $glv['apply_return'] == 0) ? 1 : 0;
            $glv['draw_str'] = order_goods_draw_str($glv['apply_return']);

        }
        $return['status'] = 1;
        $return['msg'] = '';
        $return['result'] = $goods_list;
        return $return;
    }


    /*
     * 获取账户资金记录
     * type = 1 余额
     * type = 2 积分
     */
    public function get_account_log($user_id,$type=1){
        //查询条件
//        $type = I('get.type',0);
        $where['user_id'] = $user_id;
        $field = "`desc` as msg,pay_points,user_money,change_time";
        if($type == 1){
            $where['user_money'] = ["neq",0];
            $field = "`desc` as msg,user_money,change_time";
        }
        if($type == 2){
            $where['pay_points'] = ["neq",0];
            $field = "`desc` as msg,pay_points,change_time";
        }

        $count = M('account_log')->where($where)->count();
        $Page = new Page($count,16);
        $logs = M('account_log')->where($where)->field($field)->order('change_time desc')->limit($Page->firstRow.','.$Page->listRows)->select();

        $return['status'] = 1;
        $return['msg'] = '';
        $return['result'] = $logs;
        $return['show'] = $Page->show();

        return $return;
    }
    /*
     * 获取优惠券
     */
    public function get_coupon($user_id,$type =0 ){
       
        //查询条件
        //    $type = I('get.type',0);           
     

        $where = ' AND l.order_id = 0 AND c.use_end_time > '.time(); // 未使用
        if($type == 1){
            //已使用
            $where = ' AND l.order_id > 0 AND l.use_time > 0 ';
        }
        if($type == 2){
            //已过期
            $where = ' AND '.time().' > c.use_end_time ';
        }        
        //获取数量
        $sql = "SELECT count(l.id) as total_num FROM __PREFIX__coupon_list".
            " l LEFT JOIN __PREFIX__coupon".
            " c ON l.cid =  c.id WHERE l.uid = {$user_id} {$where}";
        $count = $this->query($sql);
        $count = $count[0]['total_num'];


        $sql = "SELECT l.*,c.name,c.money,c.use_end_time,c.condition FROM __PREFIX__coupon_list".
            " l LEFT JOIN __PREFIX__coupon".
            " c ON l.cid =  c.id WHERE l.uid = {$user_id} {$where}  ORDER BY l.send_time DESC,l.use_time";

        $logs = $this->query($sql);

        $return['status'] = 1;
        $return['msg'] = '获取成功';
        $return['result'] = $logs;
        
        return $return;
    }

    /**
     * 获取商品收藏列表
     * @param $user_id  用户id
     */
    public function get_goods_collect($user_id){
        $count = M('goods_collect')->where(array('user_id'=>$user_id))->count();
        if ($count == 0) {
            $return['status'] = 1;
            $return['msg'] = '收藏列表为空';
            $return['result'] = [];
            $return['show'] = [];
        }else{
            $page = new Page($count,10);
            $show = $page->show();
            //获取我的收藏列表
            $result = M('goods_collect as c')
                    ->field('c.collect_id,c.add_time,g.goods_id,g.market_price,g.goods_name,g.goods_remark,g.shop_price,g.original_img')
                    ->join('ln_goods as g on g.goods_id=c.goods_id')
                    ->where("c.user_id=$user_id")
                    ->order('c.add_time DESC')
                    ->limit("{$page->firstRow},{$page->listRows}")
                    ->select();
            foreach($result as $kk => &$rv)
            {
                $rv['original_img'] = parseMediaUrl($rv['original_img']);
            }
            $return['status'] = 1;
            $return['msg'] = '获取成功';
            $return['result'] = $result;
            $return['show'] = $show;     
        }
            
        return $return;
    }

    /**
     * 获取评论列表
     * @param $user_id 用户id
     * @param $status  状态 0 未评论 1 已评论
     * @return mixed
     */
    public function get_comment($user_id,$status=2){
        if($status == 1){
            //已评论
            $count2 = M('')->query("select count(*) as count from `__PREFIX__comment`  as c inner join __PREFIX__order_goods as g on c.goods_id = g.goods_id and c.order_id = g.order_id where c.user_id = $user_id");
            $count2 = $count2[0]['count'];
            
            $page = new Page($count2,10);
            $sql = "select c.*,g.*,(select order_sn from  __PREFIX__order where order_id = c.order_id ) as order_sn  from  __PREFIX__comment as c inner join __PREFIX__order_goods as g on c.goods_id = g.goods_id and c.order_id = g.order_id where c.user_id = $user_id order by c.add_time desc LIMIT {$page->firstRow},{$page->listRows}";
        }else{        	
        	$countsql = " select count(1) as comment_count from __PREFIX__order_goods as og
        	left join __PREFIX__order as o on o.order_id = og.order_id where o.user_id = $user_id  and og.is_send != 0 ";
        	$where = '';
        	if($status == 0){
        		$countsql .= $where = " and og.is_comment = 0 ";
        	}
        	$comment = M()->query($countsql);
        	$count1 = $comment[0][comment_count]; // 待评价
            $page = new Page($count1,3);
            $sql =" select *  from __PREFIX__order_goods as og 
            left join __PREFIX__order as o on o.order_id = og.order_id  where o.user_id = $user_id and og.is_send != 0  
            $where order by o.order_id desc  LIMIT {$page->firstRow},{$page->listRows}";            
        }
        
        $show = $page->show();
        $comment_list = M()->query($sql);
        if($comment_list){
        	$return['result'] = $comment_list;
        	$return['show'] = $show; //分页
        	return $return;
        }else{
        	return array();
        }
    }
    
    /**
     * 添加评论
     * @param $order_id  订单id
     * @param $goods_id  商品id
     * @param $user_email用户邮箱地址
     * @param $username  用户名
     * @return bool
     */
    public function add_comment($add){
        if(!$add['goods_id'])
            return array('status'=>-1,'msg'=>'非法操作','result'=>'');
        
        //检查订单是否已完成
        $map['order_id'] = $add['order_id'];
        $order = M('order')->where($map)->find();
        if( !$order )
        {
            return array('status'=>-1,'msg'=>'订单不存在','result'=>'');
        }

        if($order['order_status'] != 2)
        {
            // doLog("[commoent]".\json_encode(I())."\n".\json_encode($add)."\n".\json_encode($order),'commoent');
            return array('status'=>-2,'msg'=>'该笔订单还未确认收货','result'=>'');
        }

        //检查是否已评论过
        $pcommentWhere['order_id'] = $add['order_id'];
        $pcommentWhere['goods_id'] = $add['goods_id'];
        $pcomment_count  = M('order_goods')->where($pcommentWhere)->find();

        if(!$pcomment_count)
        {
            return array('status'=>-4,'msg'=>'订单商品不存在','result'=>'');
        }

        if($pcomment_count['is_comment'])
        {
            return array('status'=>-4,'msg'=>'您已经评论过该商品','result'=>'');
        }
        
        $add['shop_id'] = $order['shop_id'];
        M()->startTrans();
        $row = M('comment')->add($add);
        if( !$row )
        {
            M()->rollback();
            return array('status'=>-1,'msg'=>'评价失败','result'=>'');
        }
        //更新订单商品表状态
        $updateOG = M('order_goods')->where(array(
            'goods_id'=>$add['goods_id'],
            'order_id'=>$add['order_id']
            ))->save(array('is_comment'=>1));
        if( $updateOG === false )
        {
            M()->rollback();
            return array('status'=>-1,'msg'=>'评价失败;code-1','result'=>'');
        }
        $updateG = M('goods')->where(array('goods_id'=>$add['goods_id']))->setInc('comment_count',1); // 评论数加一  
        if( $updateG === false )
        {
            M()->rollback();
            return array('status'=>-1,'msg'=>'评价失败;code-2','result'=>'');
        }
        // 查看这个订单是否全部已经评论,如果全部评论了 修改整个订单评论状态 
        $commentWhere['is_comment'] = 0;
        $commentWhere['order_id'] = $add['order_id'];
        $comment_count   = M('order_goods')->where($commentWhere)->count();
        if($comment_count == 0) // 如果所有的商品都已经评价了 订单状态改成已评价
        {
            $updateOrder = M('order')->where([
                'order_id' => $add['order_id']
            ])->save(array('order_status'=>4));
            if( $updateOrder === false )
            {
                M()->rollback();
                return array('status'=>-1,'msg'=>'评价失败;code-3','result'=>'');
            }
        }
        M()->commit();
        return array('status'=>1,'msg'=>'评论成功','result'=>'');
    }

    /**
     * 邮箱或手机绑定
     * @param $email_mobile  邮箱或者手机
     * @param int $type  1 为更新邮箱模式  2 手机
     * @param int $user_id  用户id
     * @return bool
     */
    public function update_email_mobile($email_mobile,$user_id,$type=1){
        //检查是否存在邮件
        if($type == 1)
            $field = 'email';
        if($type == 2)
            $field = 'mobile';
        $condition['user_id'] = array('neq',$user_id);
        $condition[$field] = $email_mobile;

        $is_exist = M('users')->where($condition)->find();
        if($is_exist)
        {
            throw new \Exception(-1,$email_mobile."已被注册");
        }
        unset($condition[$field]);
        $condition['user_id'] = $user_id;
        
        $validate = $field.'_validated';
        $save = array($field=>$email_mobile,$validate=>1);
        if( $type == 2 )
        {
            $user = M('users')->where($condition)->find();
            #如果改手机号，原昵称也是手机，那就改掉昵称
            if($user && $user['nickname'] && preg_match('/^[\d]{11}$/',$user['nickname']))
            {
                $save['nickname'] = $email_mobile;
            }
        }

        return M('users')->where($condition)->save($save);
    }

    /**
     * 更新用户信息
     * @param $user_id
     * @param $post  要更新的信息
     * @return bool
     */
    public function update_info($user_id,$post=array()){
        $model = M('users')->where("user_id = ".$user_id);
        $row = $model->setField($post);
        if($row === false)
           return false;
        return true;
    }

    /**
     * 地址添加/编辑
     * @param $user_id 用户id
     * @param $address_id 地址id(编辑时需传入)
     * @return array
     */
    public function add_address($user_id,$address_id=0,$data){
        $post = $data;
        if($address_id == 0)
        {
            $c = M('UserAddress')->where("user_id = $user_id")->count();
            if($c >= 20)
                return array('status'=>-1,'msg'=>'最多只能添加20个收货地址','result'=>'');
        }        
        
        //检查手机格式
        if($post['consignee'] == '')
            return array('status'=>-1,'msg'=>'收货人不能为空','result'=>'');
        if(!$post['province'] || !$post['city'] || !$post['district'])
            return array('status'=>-1,'msg'=>'所在地区不能为空','result'=>'');
        if(!$post['address'])
            return array('status'=>-1,'msg'=>'地址不能为空','result'=>'');
        if(!check_mobile($post['mobile']))
            return array('status'=>-1,'msg'=>'手机号码格式有误','result'=>'');
        if(!$post['longitude'] || !$post['latitude'] ){
            return array('status'=>-1,'msg'=>'经纬度数据有误','result'=>'');
        }
        //编辑模式
        if($address_id > 0){

            $address = M('user_address')->where(array('address_id'=>$address_id,'user_id'=> $user_id))->find();
            if($post['is_default'] == 1 && $address['is_default'] != 1)
                M('user_address')->where(array('user_id'=>$user_id))->save(array('is_default'=>0));
            $row = M('user_address')->where(array('address_id'=>$address_id,'user_id'=> $user_id))->save($post);
            if(!$row)
                return array('status'=>-1,'msg'=>'编辑失败','result'=>'');
            return array('status'=>1,'msg'=>'编辑成功','result'=>'');
        }
        //添加模式
        $post['user_id'] = $user_id;
        
        // 如果目前只有一个收货地址则改为默认收货地址
        $c = M('user_address')->where("user_id = {$post['user_id']}")->count();        
        if($c == 0)  $post['is_default'] = 1;
        $address_id = M('user_address')->add($post);
        //如果设为默认地址
        $insert_id = M()->getLastInsID();
        $map['user_id'] = $user_id;
        $map['address_id'] = array('neq',$insert_id);
               
        if($post['is_default'] == 1)
            M('user_address')->where($map)->save(array('is_default'=>0));
        if(!$address_id)
            return array('status'=>-1,'msg'=>'添加失败','result'=>'');
        
        
        return array('status'=>1,'msg'=>'添加成功','result'=>$address_id);
    }

    /**
     * 添加自提点
     * @author dyr
     * @param $user_id
     * @param $post
     * @return array
     */
    public function add_pick_up($user_id, $post)
    {
        //检查用户是否已经有自提点
        $user_pickup_address_id = M('user_address')->where('user_id=' . $user_id . ' AND is_pickup=1')->getField('address_id');
        $pick_up = M('pick_up')->where(array('pickup_id' => $post['pickup_id']))->find();
        $post['address'] = $pick_up['pickup_address'];
        $post['is_pickup'] = 1;
        $post['user_id'] = $user_id;
        if (!empty($user_pickup_address_id)) {
            //更新自提点
            M('user_address')->where(array('address_id' => $user_pickup_address_id))->save($post);
            return array('status' => 1, 'msg' => '更新成功', 'result' => '');
        } else {
            //添加自提点
            $user_address = D('UserAddress');
            $data = $user_address->create($post);
            if (!$data) {
                // 对data数据进行验证
                return array('status' => -1, 'msg' => '添加失败', 'result' => $user_address->getError());
            } else {
                // 验证通过 可以进行其他数据操作
                $user_address->add($data);
                return array('status' => 1, 'msg' => '添加成功', 'result' => '');
            }
        }
    }

    /**
     * 设置默认收货地址
     * @param $user_id
     * @param $address_id
     */
    public function set_default($user_id,$address_id){
        M('user_address')->where(array('user_id'=>$user_id))->save(array('is_default'=>0)); //改变以前的默认地址地址状态
        $row = M('user_address')->where(array('user_id'=>$user_id,'address_id'=>$address_id))->save(array('is_default'=>1));
        if(!$row)
            return false;
        return true;
    }

    /**
     * 修改密码
     * @param $user_id  用户id
     * @param $old_password  旧密码
     * @param $new_password  新密码
     * @param $confirm_password 确认新 密码
     */
    public function password($user_id,$old_password,$new_password,$confirm_password,$is_update=true){
        $data = $this->get_info($user_id);
        $user = $data['result'];
        if(strlen($new_password) < 6)
            return array('status'=>-1,'msg'=>'密码不能低于6位字符','result'=>'');
        if($new_password != $confirm_password)
            return array('status'=>-1,'msg'=>'两次密码输入不一致','result'=>'');
        //验证原密码
        if($is_update && ($user['password'] != '' && encrypt($old_password) != $user['password']))
            return array('status'=>-1,'msg'=>'密码验证失败','result'=>'');
      
        M()->startTrans();

        $row = M('users')->where("user_id='{$user_id}'")->save(array('password'=>encrypt($new_password)));

        #修改环信密码
        $Easemob = new \Common\Util\Easemob;
        $im_user = $user_id;
        $im_passwd = md5($new_password);
        $modifyIm = $Easemob->resetPassword( $im_user, $im_passwd );

        if( !$row || !$modifyIm )
        {
            M()->rollback();
            return array('status'=>-1,'msg'=>'修改失败','result'=>'');
        }
        M()->commit();
        return array('status'=>1,'msg'=>'修改成功','result'=>'');
    }

    /**
     * 取消订单
     */
    public function cancel_order($user_id,$order_id)
    {
        M()->startTrans();   
        $order = M('order')->where(array('order_id'=>$order_id,'user_id'=>$user_id))->find();
        //检查是否未支付订单 已支付联系客服处理退款
        if(empty($order))
            return array('status'=>-1,'msg'=>'订单不存在','result'=>'');
        //检查是否未支付的订单
        if($order['pay_status'] > 0 || $order['order_status'] > 0)
            return array('status'=>-1,'msg'=>'支付状态或订单状态不允许','result'=>'');
        
        //使用优惠券的情况
        $coupon = M('coupon_list')->where(array('order_id'=>$order_id))->find();
        if($coupon){
            $coupon_row = M('coupon_list')->where(array('id'=>$coupon['id']))->save(array('order_id'=>0, 'use_time'=>0));
            if(!$coupon_row)
                return array('status'=>-1,'msg'=>'操作失败','result'=>'');
        }

        $row = M('order')->where(array('order_id'=>$order_id,'user_id'=>$user_id))->save(array('order_status'=>3));
				
        $data['order_id'] = $order_id;
        $data['action_user'] = $user_id;
        $data['action_note'] = '您取消了订单';
        $data['order_status'] = 3;
        $data['pay_status'] = $order['pay_status'];
        $data['shipping_status'] = $order['shipping_status'];
        $data['log_time'] = time();
        $data['status_desc'] = '用户取消订单';        
        $log = M('order_action')->add($data);//订单操作记录		
		
        if(!$row || !$log)
        {
            M()->rollback();
            return array('status'=>-1,'msg'=>'操作失败','result'=>'');
        }
		// 订单数据回归
		$log = cancelOrderRegression($order['order_sn']);
		
		if (!$log || !$log['is_success']) {
		    M()->rollback();
		    return array('status'=>-1,'msg'=>'操作失败','result'=>'');
		}
        
        if( $order['is_groupbuy'] == 1 )
        {
            $closeGo = \Common\Logic\GroupbuyLogic::closeGroupBuyOrderSn($order['order_sn']);
			
            if( !$closeGo )
            {
                M()->rollback();
                return array('status'=>-1,'msg'=>'操作失败','result'=>'');
            }
        }
        M()->commit();
        return array('status'=>1,'msg'=>'操作成功','result'=>'');

    }

    /**
     * app发送短信验证码记录
     * @param $mobile
     * @param $code
     * @param $session_id
     */
    public function sms_log($mobile,$code,$session_id){
        //判断是否存在验证码
        $data = M('sms_log')->where(array('mobile'=>$mobile,'session_id'=>$session_id))->order('id DESC')->find();
        //获取时间配置
        $sms_time_out = tpCache('sms.sms_time_out');
        $sms_time_out = $sms_time_out ? $sms_time_out : 120;
        //120秒以内不可重复发送
        if($data && (time() - $data['add_time']) < $sms_time_out)
            return array('status'=>-1,'msg'=>$sms_time_out.'秒内不允许重复发送');
        $row = M('sms_log')->add(array('mobile'=>$mobile,'code'=>$code,'add_time'=>time(),'session_id'=>$session_id));
        if(!$row)
            return array('status'=>-1,'msg'=>'发送失败');
        //$send = sendSMS($mobile,'您好，你的验证码是：'.$code);
        $send = sendSMS($mobile,$code);
        if(!$send)
            return array('status'=>-1,'msg'=>'发送失败');
        return array('status'=>1,'msg'=>'发送成功');
    }

    /**
     * app发送短信验证码记录(使用XX的的短信平台)
     * @param $mobile
     * @param $code
     * @param $session_id
     */
    public function sms_liuniu_log($mobile,$code,$session_id){
        //判断是否存在验证码
        $data = M('sms_log')->where(array('mobile'=>$mobile,'session_id'=>$session_id))->order('id DESC')->find();
         //获取时间配置
        $sms_time_out = tpCache('sms.sms_time_out');
        $sms_time_out = $sms_time_out ? $sms_time_out : 120;
        //120秒以内不可重复发送
        if($data && (time() - $data['add_time']) < $sms_time_out)
            return array('status'=>-1,'msg'=>$sms_time_out.'秒内不允许重复发送');
        //插入
        $row = M('sms_log')->add(array('mobile'=>$mobile,'code'=>$code,'add_time'=>time(),'session_id'=>$session_id));
        if(!$row)
            return array('status'=>-1,'msg'=>'发送失败');
        //发送
        $content = "您的验证码为：".$code.",请勿泄露信息";
        $result = sendMessageRequest($mobile, $content);
        if($result['status'] == 0){
            return array('status'=>-1,'msg'=>$result['info']);
        }
        return array('status'=>1,'msg'=>'发送成功');
    }

    /**
     * 短信验证码验证
     * @param $mobile   手机
     * @param $code  验证码
     * @param $session_id   唯一标示
     * @return bool
     */
    public function sms_code_verify($mobile,$code,$session_id){
        //判断是否存在验证码
        $data = M('sms_log')->where(array('mobile'=>$mobile,'session_id'=>$session_id,'code'=>$code))->order('id DESC')->find();
        if(empty($data))
            return array('status'=>-1,'msg'=>'手机验证码不匹配');

        //获取时间配置
        $sms_time_out = tpCache('sms.sms_time_out');
        $sms_time_out = $sms_time_out ? $sms_time_out : 120;
        //验证是否过时
        if((time() - $data['add_time']) > $sms_time_out)
            return array('status'=>-1,'msg'=>'手机验证码超时'); //超时处理
        M('sms_log')->where(array('mobile'=>$mobile,'session_id'=>$session_id,'code'=>$code))->delete();
        return array('status'=>1,'msg'=>'验证成功');
    }
    
    /**
     * 发送验证码
     * @param $sender 接收人
     * @param $type 发送类型
     * @return json
     */
    public function send_validate_code($sender,$type){
    	$sms_time_out = tpCache('sms.sms_time_out');
    	$sms_time_out = $sms_time_out ? $sms_time_out : 180;
    	//获取上一次的发送时间
    	$send = session('validate_code');
    	if(!empty($send) && $send['time'] > time() && $send['sender'] == $sender){
    		//在有效期范围内 相同号码不再发送
    		$res = array('status'=>-1,'msg'=>'规定时间内,不要重复发送验证码');
    	}
    	$code =  mt_rand(1000,9999);
    	if($type == 'email'){
    		//检查是否邮箱格式
    		if(!check_email($sender))
    			$res = array('status'=>-1,'msg'=>'邮箱码格式有误');
    		$send = send_email($sender,'验证码','您好，你的验证码是：'.$code);
    	}else{
    		if(!check_mobile($sender))
    			$res = array('status'=>-1,'msg'=>'手机号码格式有误');
    			//$send = sendSMS($sender,'您好，你的验证码是：'.$code);
                $send = sendSMS($sender,$code);
    	}
    	if($send){
    		$info['code'] = $code;
    		$info['sender'] = $sender;
    		$check['is_check'] = 0;
    		$info['time'] = time() + $sms_time_out; //有效验证时间
    		session('validate_code',$info);
    		$res = array('status'=>1,'msg'=>'验证码已发送，请注意查收');
    	}else{
    		$res = array('status'=>-1,'msg'=>'验证码发送失败,请联系管理员');
    	}
        return $res;
    }

    /**
     * 发送验证码
     * @param $sender 接收人
     * @param $type 发送类型
     * @return json
     */
    public function send_validate_code_liuniu($sender,$type){
        $sms_time_out = tpCache('sms.sms_time_out');
        $sms_time_out = $sms_time_out ? $sms_time_out : 180;
        //获取上一次的发送时间
        $send = session('validate_code');
        if(!empty($send) && $send['time'] > time() && $send['sender'] == $sender){
            //在有效期范围内 相同号码不再发送
            $res = array('status'=>-1,'msg'=>'规定时间内,不要重复发送验证码');
        }
        $code =  mt_rand(1000,9999);
        if($type == 'email'){
            //检查是否邮箱格式
            if(!check_email($sender))
                $res = array('status'=>-1,'msg'=>'邮箱码格式有误');
            $send = send_email($sender,'验证码','您好，你的验证码是：'.$code);
        }else{
            if(!check_mobile($sender))
                $res = array('status'=>-1,'msg'=>'手机号码格式有误');
                //$send = sendSMS($sender,'您好，你的验证码是：'.$code);
                //$send = sendSMS($sender,$code);
                //发送
                $result = sendMessageRequest($sender, $code);
                if($result['status'] == 0){
                    return array('status'=>-1,'msg'=>$result['info']);
                } else {
                    $send = true;
                }
        }
        if($send){
            $info['code'] = $code;
            $info['sender'] = $sender;
            $check['is_check'] = 0;
            $info['time'] = time() + $sms_time_out; //有效验证时间
            session('validate_code',$info);
            $res = array('status'=>1,'msg'=>'验证码已发送，请注意查收');
        }else{
            $res = array('status'=>-1,'msg'=>'验证码发送失败,请联系管理员');
        }
        return $res;
    }
    
    public function check_validate_code($code,$sender){   	
    	$check = session('validate_code');
    	if(empty($check))
    	{
    		$res = array('status'=>0,'msg'=>'请先获取验证码');
    	}elseif($check['time']<time())
    	{
    		$res = array('status'=>0,'msg'=>'验证码已超时失效');
    	}elseif($code!=$check['code'] || $check['sender']!=$sender)
    	{
    		$res = array('status'=>0,'msg'=>'验证失败,验证码有误');
    	}else
    	{
    		$check['is_check'] = 1; //标示验证通过
    		session('validate_code',$check);
    		$res = array('status'=>1,'msg'=>'验证成功');
    	}
    	return $res;
    }

    /**
     * @time 2016/09/01
     * @author dyr
     * 设置用户系统消息已读
     */
    public function setSysMessageForRead()
    {
        $user_info = session('user');
        if (!empty($user_info['user_id'])) {
            $data['status'] = 1;
            M('user_message')->where(array('user_id' => $user_info['user_id'], 'category' => 0))->save($data);
        }
    }

    /**
     * App修改密码
     * @param $user_id  用户id
     * @param $new_password  新密码
     */
    public function passwordForApp($user_id,$old_password,$new_password,$mobile,$unique_id){
        $data = $this->get_info($user_id);
        $user['password'] = $data['password'];//旧密码
        //验证原密码
         if($user['password'] != '' && encrypt($old_password) != $user['password'])
            return array('status'=>-1,'msg'=>'原密码有误','result'=>'');

          //获取时间配置
        $sms_time_out = tpCache('sms.sms_time_out');
        $sms_time_out = $sms_time_out ? $sms_time_out : 120;
        //120秒以内不可重复发送
        $data = M('sms_log')->where(array('mobile'=>$mobile,'session_id'=>$unique_id))->order('id DESC')->find();
        if(!$data){
            exit(json_encode(array('status'=>-1,'msg'=>'短信验证码错误','result'=>'')));
        }else if((time() - $data['add_time']) > $sms_time_out ){
            //验证码过期
            exit(json_encode(array('status'=>-1,'msg'=>'短信验证码过期','result'=>'')));
        }
            
        $user = M('users')->where("mobile =$mobile")->find();
        if(empty($user)){
            exit(json_encode(array('status'=>-1,'msg'=>'该手机号码没有关联账户','result'=>'')));
        }
        $map['password'] = $new_password;
        $row = M('users')->where("user_id=$user_id")->save($map);
        #修改环信密码
        $Easemob = new \Common\Util\Easemob;
        $im_user = $user_id;
        $im_passwd = $new_password;
        $modifyIm = $Easemob->resetPassword( $im_user, $im_passwd );
        if( !$row || !$modifyIm )
        {
            return array('status'=>-1,'msg'=>'修改失败','result'=>'0');
        }
        return array('status'=>1,'msg'=>'修改成功','result'=>'1');
}

    /**
     * 获取用户等级名称
     * @param $user_level
     * @return mixed
     */
    public function getLevelName($user_level){
        $level = M('user_level')->select();
        $level = convert_arr_key($level,'level_id');
        return $level[$user_level]['level_name'];
    }

    /**
     * 获取分享链接
     * @param user_info
     * @param sence
     */ 
    public function getShareLink($user_info = [],$sence = '')
    {
        #SITE_URL."/index.php?m=Mobile&c=App&a=index&InCode={$user['leader']}";
        $baseUrl = SITE_URL."/Mobile/App/index";
        $query = [];
        if( $user_info )
        {
            if( isset($user_info['leader']) )
            $query['incode'] = $user_info['leader'];
            if( isset($user_info['user_id']) )
            $query['uuid'] = $user_info['user_id'];
        }

        if( $sence )
        {
            $query['sence'] = $sence;
        }
        return $baseUrl.( $query ? "?".http_build_query($query) : "" );
    }

    /**
     * 生成邀请码(唯一)
     * @param length
     * @return string
     */
    protected function createInCode($length = 4)
    { 
        $char = '123456789ABCDEFGHJKLMNPQRSTUVWXYZ';
        if(!is_int($length) || $length < 0) {
            return "";
        }
    
        $string = '';
        for($i = $length; $i > 0; $i--) {
            $string .= $char[mt_rand(0, strlen($char) - 1)];
        }

        $log = M("users")->field("user_id,leader")->where([
            "leader" => $string
        ])->find();

        if($log)
        {
            return $this->createInCode($length);
        }
    
        return $string; 
    }

    /**
     * 申请退款
     * @param $add
     * @return array
     */
    public function add_drawback($add){
        if(!$add['order_id']){
            return array('status'=>-1,'msg'=>'非法操作','result'=>'');
        }
        if(floatval($add['money']) <= 0){
            return array('status'=>-1,'msg'=>'请填写退款金额', 'result'=>'');
        }

        //检查订单是否已完成
        $orderModel = M('order');
        $map['order_id'] = $add['order_id'];
        $order = $orderModel->where($map)->find();
        if( !$order ) {
            return array('status'=>-1,'msg'=>'订单不存在','result'=>'');
        }

        if($order['pay_status']  != 1){
            return array('status'=>-1,'msg'=>'该笔订单还未支付','result'=>'');
        }

        if($order['shipping_status']  != 1) {
            return array('status'=>-1,'msg'=>'该笔订单还未发货','result'=>'');
        }

        //检查是否已申请退款
        $drawbackWhere['order_id'] = $add['order_id'];
        $drawback_info  = M('drawback')->where($drawbackWhere)->find();

        if($drawback_info)
        {
            return array('status'=>-1,'msg'=>'您已申请过退款','result'=>'');
        }
        M()->startTrans();
        $row = M('drawback')->add($add);
        if( !$row ) {
            M()->rollback();
            return array('status'=>-1,'msg'=>'申请失败','result'=>'');
        }
        $update_order = $orderModel->where(array('order_id'=>$add['order_id']))->setField('is_drawback', 1);
        if( $update_order === false)
        {
            M()->rollback();
            return array('status'=>-1,'msg'=>'订单操作失败','result'=>'');
        }

        add_shop_message($order['shop_id'], '申请退款', '您有新的退款申请，请前往查看处理',1, $add['order_id']);

        M()->commit();
        return array('status'=>1,'msg'=>'申请成功','result'=>$row);
    }
}